package com.lmb.service.impl;

import com.lmb.annotation.LogMethod;
import com.lmb.bean.UserLogin;
import com.lmb.mapper.UserLoginDao;
import com.lmb.service.LoginService;
import com.lmb.util.PasswordUtil;
import com.lmb.util.SyS;
import com.lmb.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    UserLoginDao userLoginDao;

    public UserLogin getlogin(String token){
        Object id=TokenUtil.getUsername(token, SyS.TOKEN_USER_ID);
        if (id==null){
            TokenUtil.removeToken(token);
            throw new RuntimeException("登录异常");

        }
        UserLogin userLogin = userLoginDao.one(Integer.parseInt(id.toString()));
        return userLogin;
    }
    @Override
    @LogMethod(serviceName = "用户登录")
    public String login(UserLogin userLogin) {
        //登录逻辑
        //1.通过用户名查询数据库
        UserLogin result=userLoginDao.getByusername(userLogin.getUser_name());
        if(result==null){
            return "用户不存在";
        }
        //2.判断密码
        String password=userLogin.getUser_password();
        String encryptionPassword= result.getUser_password();
        if(!PasswordUtil.checkPassword(password,encryptionPassword)){
            throw new RuntimeException("密码错误");
        }
        String token= TokenUtil.getUserToken(result.getUser_id(), result.getUser_name());        //3.返回结果
        return token;
    }
}
